import React, { useEffect, useState } from 'react';
import { View, Text } from '@tarojs/components';
import PageContainer from '@/components/PageContainer';
import { getRechargePackageList, getRecorderDetail, payRechargePackage } from '@/services/payment';
import FlexScrollView from '@/components/FlexScrollView';
import './index.less';
import { DynamicColors, GStyleSheet } from '@/utils/DarkMode';
import Taro from '@tarojs/taro';
import userState from '@/models/userState';
import { sleep } from '@/utils';
import { payHandler } from './unit';
import { getWechatId } from '@/utils/loginStatus';

const dstyle = GStyleSheet.create({
  list: {
    paddingTop: 20,
    paddingLeft: 20,
    paddingRight: 20,
  },
  noticeText: {
    color: DynamicColors.tintColor,
  },
  title: {
    fontSize: 16,
    marginBottom: 16,
    color: DynamicColors.normalTextColor,
    display: 'flex',
    flexDirection: 'row',
    justifyContent: 'space-between',
  },
  packagesContainer: {
    display: 'flex',
    flexDirection: 'row',
    flexWrap: 'wrap',
    gap: 12,
  },
  packageItem: {
    flex: '0 0 calc(50% - 6px - 26px)',
    height: 100,
    backgroundColor: DynamicColors.cardBackgroundColor,
    borderRadius: 8,
    padding: 12,
    borderWidth: 1,
    borderStyle: 'solid',
    borderColor: 'rgba(0,0,0,0)',
    display: 'flex',
    flexDirection: 'column',
    alignItems: 'flex-start',
    justifyContent: 'space-between',
  },
  packageItemSelected: {
    borderColor: DynamicColors.tintColor,
    borderWidth: 1,
    borderStyle: 'solid',
  },
  coinAmount: {
    fontSize: 16,
    fontWeight: 'bold',
    color: DynamicColors.normalTextColor,
  },
  desc: {
    fontSize: 12,
    color: DynamicColors.normalTextGaryColor,
    marginTop: 4,
  },
  priceContainer: {
    display: 'flex',
    flexDirection: 'row',
    alignItems: 'center',
    marginTop: 8,
  },
  discountPrice: {
    fontSize: 20,
    color: DynamicColors.tintColor,
    fontWeight: 'bold',
  },
  originalPrice: {
    fontSize: 14,
    color: DynamicColors.normalTextGaryColor,
    marginLeft: 8,
    textDecoration: 'line-through',
  },
  paymentMethod: {
    marginTop: 24,
  },
  methodItem: {
    display: 'flex',
    alignItems: 'center',
    padding: 12,
    backgroundColor: DynamicColors.cardBackgroundColor,
    borderRadius: 8,
    marginTop: 12,
  },
  methodIcon: {
    width: 24,
    height: 24,
    marginRight: 8,
  },
  methodText: {
    flex: 1,
    color: DynamicColors.normalTextColor,
  },
  submitButton: {
    backgroundColor: DynamicColors.tintColor,
    borderRadius: 22,
    display: 'flex',
    height: 44,
    alignItems: 'center',
    width: '80%',
    justifyContent: 'center',
  },
  submitText: {
    color: '#fff',
    fontSize: 16,
  },
  notice: {
    fontSize: 12,
    color: DynamicColors.normalTextGaryColor,
    marginTop: 8,
    marginBottom: 8
  },
  bottomGroup: {
    position: 'fixed',
    bottom: 24,
    width: '100%',
    display: 'flex',
    flexDirection: 'column',
    justifyContent: 'center',
    alignItems: 'center',
  },
});

interface Package {
  id: string;
  name: string;
  desc: string;
  price: number;
  discount_price: number;
  icon_url: string;
  create_time: number;
  update_time: number;
}

const Packages: React.FC = () => {
  const router = Taro.getCurrentInstance()?.router;
  const id = router?.params?.id;
  const type = router?.params?.type;
  const styles = dstyle.useDynamicStyle();
  const [selectedPackage, setSelectedPackage] = useState<string>('');
  const [packages, setPackages] = useState<Package[]>([]);

  useEffect(() => {
    getRechargePackageList({type}).then((res) => {
      if (res.success) {
        setPackages(res.data.data);
        if (res.data.data.length > 0) {
          setSelectedPackage(res.data.data[0].id);
        }
      }
    });
  }, []);

  const handleSubmit = async () => {
    // 处理充值逻辑
    const openid = await getWechatId();
    console.log('openidopenidopenidopenidopenid', openid)
    Taro.showLoading({
      title: '充值中...',
    });
    const orderData = await payRechargePackage({id: selectedPackage, openid, deviceId: id});
    if (orderData.success) {
      // 调用微信支付
      const payData = orderData.data.data.pay_info
      const res = await payHandler(orderData.data.data.id, payData)
      Taro.navigateTo({url: '/pages/payment/record'});
      // if (res.data.event === 'success') {
      //     setTimeout(() => {
      //       // 跳转到充值记录
      //       Taro.navigateTo({url: '/pages/payment/record'});
      //     }, 2000);
      // }
    } else {
      Taro.showToast({
        title: '创建订单失败',
        icon: 'none',
      });
    }
    Taro.hideLoading();
  };

  return (
    <PageContainer title="充值">
      <FlexScrollView id='deleteScrollList' scrollStyle={styles.list}>
        <View style={styles.title}>
          <Text>充值套餐</Text>
          {/* <Text style={styles.recordText} onClick={() => Taro.navigateTo({url: '/pages/payment/record'})}>
            充值记录
          </Text> */}
        </View>
        <View style={styles.packagesContainer}>
          {packages.map((pkg) => (
            <View
              key={pkg.id}
              style={{
                ...styles.packageItem,
                ...(selectedPackage === pkg.id && styles.packageItemSelected)
              }}
              onClick={() => setSelectedPackage(pkg.id)}
            >
              <Text style={styles.coinAmount}>{pkg.name}</Text>
              <Text style={styles.desc}>{pkg.desc}</Text>
              <View style={styles.priceContainer}>
                <Text style={styles.discountPrice}>¥{pkg.discount_price}</Text>
                {pkg.discount_price !== pkg.price && (
                  <Text style={styles.originalPrice}>¥{pkg.price}</Text>
                )}
              </View>
            </View>
          ))}
        </View>
      </FlexScrollView>

      <View style={styles.bottomGroup}>
        <View style={styles.notice}>
          点击立即充值，即表示您已阅读并同意<Text style={styles.noticeText}>《充值协议》</Text>
        </View>
        <View style={styles.submitButton} onClick={handleSubmit}>
          <Text style={styles.submitText}>去充值</Text>
        </View>
      </View>
    </PageContainer>
  );
};

export default Packages;